package com.example.administrator.szb.fragments.fragmenttool;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.bumptech.glide.Glide;
import com.example.administrator.szb.R;
import com.example.administrator.szb.activity.WebViewActivity;
import com.example.administrator.szb.adapter.BaseAdapter;
import com.example.administrator.szb.common.SetStatusBar;
import com.example.administrator.szb.fragments.base.BaseFragment;
import com.example.administrator.szb.bean.ZXBean;
import com.example.administrator.szb.tinkerutil.SampleApplicationLike;
import com.example.administrator.szb.http.HttpUtil;
import com.example.administrator.szb.http.URLAddress;
import com.example.administrator.szb.util.GetJsonDataUtil;
import com.example.administrator.szb.util.Toasts;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.api.OnRefreshLoadmoreListener;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by Administrator on 2017/9/5.
 */

public class FragmentZX extends BaseFragment {
    View view;
    @Bind(R.id.zx_recyclerview)
    RecyclerView zxRecyclerview;
    @Bind(R.id.zx_fragment_swiperefreshlayout)
    SmartRefreshLayout zxFragmentSwiperefreshlayout;
    int current_page = 1 ;
    int per_page = 10;
    ZXBean zxBean;
    BaseAdapter<ZXBean.DataBean.ListBean> adapter;
    View footerview;
    ArrayList<ZXBean.DataBean.ListBean> mdata = new ArrayList<>();
    private boolean isFirstEnter = true;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_zx, container, false);
        SetStatusBar.setBar(view,getContext());
        ButterKnife.bind(this, view);
        footerview = LayoutInflater.from(getActivity()).inflate(R.layout.view_wd_footer, null);
        footerview.setVisibility(View.INVISIBLE);
        initView();
        return view;
    }

    private void initView() {
        initRefreshLayout();
        initRecyclerview();
    }

    private void requestData(final int isRefreshOrMore) {
        HashMap<String,String> map = new HashMap<>();
        map.put("code", HttpUtil.getParam());
        map.put("current_page",current_page+"");
        map.put("per_page",per_page+"");
        String json = GetJsonDataUtil.simpleMapToJsonStr(map);
        String url = URLAddress.URLBASE + URLAddress.URL_ZX;
        HttpUtil.RequestGsonPost(SampleApplicationLike.getQueueInstance(), Request.Method.POST, ZXBean.class, URLAddress.URLBASE + URLAddress.URL_ZX, map, new Response.Listener() {
            @Override
            public void onResponse(Object response) {
                zxBean = (ZXBean) response;
                getActivity().findViewById(R.id.zx_net_error_include).setVisibility(View.GONE);
                if (zxBean.getResult() == 1){
                    //initRecyclerview();
                    if (isRefreshOrMore == 0) {
                        mdata.clear();
                        mdata.addAll(zxBean.getData().getList());
                        zxFragmentSwiperefreshlayout.finishRefresh();
                        current_page = Integer.parseInt(zxBean.getData().getCurrent_page())+1;
                        // Toasts.show(getActivity(), "刷新成功", Toast.LENGTH_SHORT);
                    }else if(isRefreshOrMore == 1){
                        if (zxBean.getData().getList().size()>0){
                            current_page = Integer.parseInt(zxBean.getData().getCurrent_page())+1;
                            mdata.addAll(zxBean.getData().getList());
                        }else{
                            //Toasts.show(getActivity(), "没有数据了", Toast.LENGTH_SHORT);
                        }


                        zxFragmentSwiperefreshlayout.finishLoadmore();
                    }
                    adapter.notifyDataSetChanged();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                zxFragmentSwiperefreshlayout.finishRefresh();
                footerview.setVisibility(View.INVISIBLE);
                getActivity().findViewById(R.id.zx_net_error_include).setVisibility(View.VISIBLE);
                getActivity().findViewById(R.id.zx_net_error_include).findViewById(R.id.home_fragment_button_djcs_error).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        requestData(0);
                    }
                });
                Toasts.show(getActivity(), "网络异常。。。", Toast.LENGTH_SHORT);
            }
        });
    }

    private void initRecyclerview() {
        //initRefreshLayout();

        zxRecyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
        adapter = new BaseAdapter<ZXBean.DataBean.ListBean>(getActivity(),mdata) {
            @Override
            public void convert(int position, BaseViewHolder holder, ZXBean.DataBean.ListBean listBean) {
                ((TextView)holder.getView(R.id.title)).setText(listBean.getTitle());
                ((TextView)holder.getView(R.id.time)).setText(listBean.getCreate_time());
                ((ImageView)holder.getView(R.id.head_img)).setVisibility(View.GONE);
                ((TextView)holder.getView(R.id.liulan)).setText(listBean.getReading_num()+"人浏览");
                holder.getView(R.id.lines2).setVisibility(View.VISIBLE);
                if (TextUtils.isEmpty(listBean.getImage())) {
                    //(holder.getView(R.id.imageView23)).setVisibility(View.GONE);
                }else{
                    Glide.with(getActivity()).load(listBean.getImage()).placeholder(R.mipmap.defaultimg).into(((ImageView)holder.getView(R.id.head_img)));
                    ((ImageView)holder.getView(R.id.head_img)).setVisibility(View.VISIBLE);
                }
            }

            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_shocang_zx;
            }
        };
        //com.example.administrator.szb.adapter.addFootView(footerview);
        adapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = new Intent(getActivity(), WebViewActivity.class);
                intent.putExtra("wz_id",mdata.get(position).getId());
                intent.putExtra("title",mdata.get(position).getTitle());
                intent.putExtra("image",mdata.get(position).getImage());
                startActivity(intent);
            }
        });

        zxRecyclerview.setAdapter(adapter);
        //loadMore();//开启加载更多监听
    }


    /**
     * 开启刷新监听
     */
    private void initRefreshLayout() {
//        zxFragmentSwiperefreshlayout.setColorSchemeResources(R.color.zhutise);
//        zxFragmentSwiperefreshlayout.post(new Runnable() {
//            @Override
//            public void run() {
//                current_page = 1;
//                zxFragmentSwiperefreshlayout.setRefreshing(true);
//                requestData(0);
//            }
//        });
//
//        zxFragmentSwiperefreshlayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
//            @Override
//            public void onRefresh() {
//                current_page = 1;
//                zxFragmentSwiperefreshlayout.setRefreshing(true);
//                requestData(0);
//            }
//        });

        if (isFirstEnter) {
            isFirstEnter = false;
            zxFragmentSwiperefreshlayout.autoRefresh();
        }
        zxFragmentSwiperefreshlayout.setEnableLoadMore(true);//是否启用上拉加载功能
        zxFragmentSwiperefreshlayout.setEnableLoadMoreWhenContentNotFull(true);//是否在列表不满一页时候开启上拉加载功能


        zxFragmentSwiperefreshlayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                //refreshlayout.setLoadmoreFinished(false);//恢复上拉状态
                // Toasts.show(getActivity(), "加载更多啊", Toast.LENGTH_SHORT);
                requestData(1);
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                current_page = 1;
                requestData(0);
                //refreshlayout.finishRefresh();
            }
        });
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

}
